package cn.lsl.server;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.URLDecoder;
import java.util.StringTokenizer;

public class TServer {

    private final static int PORT = 8089;

    public static void main(String[] args) {
        try {
            ServerSocket server = new ServerSocket(PORT); // 根据端口号开启一个ServerSocket
            ServletHandler servletHandler = new ServletHandler(server);
            servletHandler.start(); // 启动一个新ServerSocket线程
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static class ServletHandler extends Thread {
        ServerSocket server = null;

        public ServletHandler(ServerSocket server) {
            this.server = server;
        }

        @Override
        public void run() {
            while (true) {
                try {
                    Socket client = null;
                    client = server.accept(); // ServerSocket阻塞,等待客户端请求服务器
                    if (client != null) {
                        try {
                            System.out.println("接受到一个客户端请求...");

                            // 根据客户端的Socket对象获取输入流对象
                            // 封装字节流到字符流
                            BufferedReader reader = new BufferedReader(new InputStreamReader(client.getInputStream()));

                            // HTTP 请求由三部分组成:请求行\消息报头\请求正文
                            String line = reader.readLine();

                            System.out.println("line:" + line);

                            // 拆分HTTP请求路径,取HTTP需要请求资源的完整路径
                            String resource = line.substring(line.indexOf('/'), line.lastIndexOf('/') - 5);

                            System.out.println("资源请求路径：" + resource);

                            // 设置编码为utf-8
                            resource = URLDecoder.decode(resource, "UTF-8");

                            // 获取此次请求的类型 GET 或 POST
                            String method = new StringTokenizer(line).nextElement().toString();

                            System.out.println("请求类型为：" + method);

                            // 逐行打印客户端浏览器发来的请求头信息
                            while ((line = reader.readLine()) != null) {
                                if (line.equals("")) break;
                                System.out.println("请求头：" + line);
                            }

                            // 如果是POST请求则直接在终端打印提交上来的信息
                            if ("post".equals(method.toLowerCase())) {
                                System.out.println("POST 请求体：" + reader.readLine());
                            } else if ("get".equals(method.toLowerCase())) {
                                // 根据HTTP请求资源后缀确定返回信息

                                // 后缀为.png则返回服务器里的一张all.png图片
                                if (resource.endsWith(".png")) {
                                    transferFileHandler("E:\\IdeaProjects\\TomcatServer\\all.png", client);
                                    closeSocket(client);
//                                    continue;
                                } else {
                                    // 如果请求后缀不是.png,则返回一个网页
                                    // 将html代码以字节流的形式写到io中,反馈给客户端浏览器
                                    // 浏览器会根据HTTP报文"Content-Type"判断服务器返回数据类型,并作出相应的解析
                                    PrintStream printer = new PrintStream(client.getOutputStream(), true);
                                    printer.println("HTTP/1.0 200 OK"); // 返回应答消息,并结束应答
//                                  printer.println("HTTP/1.0 404 Not found");
                                    printer.println("Content-Type: text/html;charset=UTF-8");
                                    printer.println();// 根据HTTP协议，空行将结束头消息

                                    printer.println("<html><body>");
                                    printer.println("<h1>欢迎使用TomcatServer</h1>");
                                    printer.println("<a href='www.baidu.com'>打开百度</a>");
                                    printer.println("</body></html>");

                                    printer.close();

                                    closeSocket(client); // 请求资源处理完毕，关闭socket连接
//                                    continue;
                                }
                            }
                        } catch (Exception e) {
                            System.out.println("HTTP 服务器错误：" + e.getMessage());
                            e.printStackTrace();
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        private void closeSocket(Socket client) {
            try {
                client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            System.out.println(client + " 离开了HTTP服务器");
        }

        private void transferFileHandler(String path, Socket client) {
            File file = new File(path);

            if (file.exists() && !file.isDirectory()) {
                try {
                    // 根据socket获取输出流对象，将访问对象写入到输出流中
                    PrintStream printer = new PrintStream(client.getOutputStream());
                    printer.println("HTTP/1.0 200 OK");
                    printer.println("Content-Type: application/binary");
                    printer.println("Content-Length: " + file.length()); // 返回内容字节数
                    printer.println();

                    FileInputStream fis = new FileInputStream(file);
                    byte[] buf = new byte[fis.available()];
                    fis.read(buf);
                    printer.write(buf);
                    printer.close();
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
